package kr.co.happenstance;

import kr.co.happenstance.util.AndroidUtil;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gcm.GCMBaseIntentService;

/**
 * GCM Service 클래스
 * 
 * @author Administrator
 *
 */
public class GCMIntentService extends GCMBaseIntentService {
	protected static final String TAG = "<<<GCMIntentService>>>";
	
	public static final String PROJECT_ID = "1085607384090";
	
	//public 기본 생성자를 무조건 만들어야 한다.
	public GCMIntentService(){
		super(PROJECT_ID);
	}
	
	/**
	 * 에러 발생시
	 */
	@Override
	protected void onError(Context context, String errorId) {
		Log.d(TAG, "onError. errorId : "+errorId);
		
	}
	
	/**
	 * 푸쉬로 받은 메세지
	 */
	@Override
	protected void onMessage(Context context, Intent intent) {
		Bundle b = intent.getExtras();
		
		String title = b.getString("title");
		String subTitle = b.getString("subTitle");
		String ticker = b.getString("ticker");
		String matchingRequestSeq = b.getString("matchingRequestSeq");
		
		
		Log.d(TAG, "title["+title+"]");
		Log.d(TAG, "subTitle["+subTitle+"]");
		Log.d(TAG, "ticker["+ticker+"]");
		Log.d(TAG, "matchingRequestSeq["+matchingRequestSeq+"]");
		
		
		setNotification(context, title, subTitle, ticker, matchingRequestSeq);
	}
	
	/**
	 * 단말에서 GCM 서비스 등록 했을 때 등록 id를 받는다
	 */
	@Override
	protected void onRegistered(Context context, String regId) {
		Log.d(TAG, "onRegistered() regId["+regId+"]");
		
		AndroidUtil.setAppPreferences(context, C.SHARED_PREF_NAME, C.SHARED_PREF_KEY_GCMID, regId);
		
	}
	
	/**
	 * 단말에서 GCM 서비스 등록 해지를 하면 해지된 등록 id를 받는다
	 */
	@Override
	protected void onUnregistered(Context context, String regId) {
		Log.d(TAG, "onUnregistered. regId : "+regId);

	}

	@SuppressWarnings("deprecation")
	private void setNotification(Context context, String title, String subTitle, String ticker, String matchingRequestSeq) {
		//출력 아이콘
		int icon = context.getApplicationInfo().icon;
		Notification noti;
		
		boolean isPackageRunning = AndroidUtil.isRunningProcess(context, context.getPackageName());
		Log.d(TAG, "isPackageRunning["+isPackageRunning+"]");
		
		Intent intent = null;
		if(isPackageRunning){
			handleMessage(ticker);
		}else{
			intent = new Intent(context, IntroActivity.class);
			intent.putExtra("notiFlag", true);			
			intent.putExtra("matchingRequestSeq", Integer.parseInt(matchingRequestSeq));
			
		}
		
		
		if(intent != null){
			PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,  PendingIntent.FLAG_UPDATE_CURRENT);
			
			if(Build.VERSION.SDK_INT >= 11){
				noti = new Notification.Builder(context)
				.setContentTitle(title)
				.setContentText(subTitle)
				.setTicker(ticker)
				.setSmallIcon(R.drawable.icon)
				.setContentIntent(pIntent)
				.getNotification();
			}else{
				noti = new Notification(icon, ticker, System.currentTimeMillis());
				noti.setLatestEventInfo(context, title, subTitle, pIntent);
			}
			
			//확인시 아이콘 사라짐 셋팅
			noti.flags |= Notification.FLAG_AUTO_CANCEL;
			
			//사운드 설정
			String curSound = AndroidUtil.getAppPreferences(context, C.SHARED_PREF_NAME, C.SHARED_PREF_KEY_SOUND);
			if(curSound.equals("")){
				curSound = Integer.toString(C.SETTING_SOUND_ON);
			}
			if(Integer.parseInt(curSound) == C.SETTING_SOUND_ON){
				noti.defaults |= Notification.DEFAULT_SOUND;
			}
			
			
			NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManager.notify(0, noti);			
		}

		
	}	
	
	private void handleMessage(final String msg){
		Thread t = new Thread(){
			public void run(){
				Message myMessage = new Message();
				Bundle resBundle = new Bundle();
				resBundle.putString( "message", msg);
				myMessage.setData( resBundle );
				handler.sendMessage(myMessage);
			}
		};
		t.start();
	}
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			Toast.makeText(getBaseContext(), msg.getData().getString("message"), Toast.LENGTH_LONG ).show();
		}
	};
	
	
	
}
